import {getToken, setToken,removeToken} from '../../until/auth'
import { login,getInfo } from "../../api/user";
import { resetRouter } from '../../router/router'

const state = {
    roles:[],
    token:getToken()
}

const mutations = {
    SET_TOKEN(state,token){
        state.token = token
    },
    SET_ROLES(state,roles){
        state.roles = roles
    },
}

const actions = {
    login({ commit },userInfo){
        const { username, password } = userInfo
        return new Promise((resolve,reject)=>{
            login({username:username.trim(),password:password}).then(response=>{
                const {data}  = response
                console.log(data)
                console.log(response)
                commit('SET_TOKEN',data.token)
                setToken(data.token)
                resolve()
            }).catch(error=>{
                console.log(error)
                reject(error)
            })

        } )
    },
    getInfo({ commit }){
        return new Promise((resolve,reject)=>{
            getInfo().then(response=>{
                const { data } = response
                if(!data){
                    reject('验证失败，请重新登录')
                }
                const { roles } = data
                if (!roles || roles.length <= 0) {
                    reject('角色不能为空')
                }
                commit('SET_ROLES', roles)
                resolve(data)
            }).catch(error=>{
                reject(error)
            })
        })
    },
    // remove token
    resetToken({ commit }) {
        return new Promise(resolve => {
            commit('SET_TOKEN', '')
            commit('SET_ROLES', [])
            removeToken()
            resolve()
        })
    },
    // user logout
    logout({ commit, dispatch }) {
        return new Promise((resolve, reject) => {
            try{
                commit('SET_TOKEN', '')
                commit('SET_ROLES', [])
                removeToken()
                resetRouter()
                // reset visited views and cached views
                // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
                dispatch('tagsView/delAllVisitedView', {}, { root: true })
                resolve()
            }catch (e) {
                reject(e)
            }


        })
    },

}
export default{
    namespaced:true,
    state,
    mutations,
    actions
}
